package mysql_servers

import (
	"gc-rds-ha/internal/dao"

	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

var (
	tableCountMysqlServersRecord uint32 = 1 //分表数量
)

type MysqlServersRecord struct {
	dao.DefaultField

	HostGroupID int
	HostName    string
	Port        uint32

	Tx *gorm.DB `gorm:"-"`
}

// TableName 表名
func (d *MysqlServersRecord) TableName() string {
	name := "mysql_servers_record"
	return name
}

// Model 模型
func (d *MysqlServersRecord) Model() *gorm.DB {
	db := dao.DB
	if d.Tx != nil {
		db = d.Tx
	}

	return db.Table(d.TableName()).Model(d)
}

// Create 创建
func (d *MysqlServersRecord) Create() error {
	m := d.Model()
	if err := m.Create(d).Error; err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("m.Create(data) error")
	}
	return nil
}

// Get 获取
func (d *MysqlServersRecord) Get() error {
	m := d.Model()

	if d.ID != 0 {
		m = m.Where("id = ?", d.ID)
	}

	if err := m.Order("id asc").First(d); err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("m.Create(d) error")
	}
	return nil
}

func CreateTableMysqlServersRecord() {
	d := &MysqlServersRecord{}
	for i := uint32(0); i < d.TableCount(); i++ {
		if err := dao.DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(d); err != nil {
			log.WithField("", log.Fields{"err": err, "tableName": d.TableName()}).Error("DB AutoMigrate Failed")
		}
	}
}

// TableCount 分表数量
func (d *MysqlServersRecord) TableCount() uint32 {
	return tableCountMysqlServersRecord
}
